package xin.nick.demo;

import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @Auther: Nick inickning@outlook.com
 * @Date: 2021/2/27 11:41
 * @Description:
 */
public class MyHystrixCollapser extends HystrixCollapser<List<String>, String, String> {
    private final String name;


    public MyHystrixCollapser(String name) {
        this.name = name;
    }

    public String getRequestArgument() {
        return name;
    }

    protected HystrixCommand<List<String>> createCommand(Collection<CollapsedRequest<String, String>> collection) {
        return new BatchCommand(collection);
    }

    protected void mapResponseToRequests(List<String> strings, Collection<CollapsedRequest<String, String>> collection) {
        int count = 0;

        for(CollapsedRequest<String, String> request: collection) {
            request.setResponse(strings.get(count++));
        }
    }

    private static final class BatchCommand extends HystrixCommand<List<String>> {

        private final Collection<CollapsedRequest<String, String>> requests;

        private BatchCommand(Collection<CollapsedRequest<String, String>> requests) {
            super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"))
                    .andCommandKey(HystrixCommandKey.Factory.asKey("GetValueForKey")));
            this.requests = requests;
        }

        protected List<String> run() throws Exception {

            System.out.println(" 真正执行请求......");
            ArrayList<String> response = new ArrayList<String>();
            for (CollapsedRequest<String, String> request : requests) {
                response.add(" 返回结果 : " + request.getArgument());
            }
            return response;
        }
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        HystrixRequestContext context = HystrixRequestContext.initializeContext();
        Future<String> f1 = new MyHystrixCollapser("Nick").queue();
        Future<String> f2 = new MyHystrixCollapser("NickN").queue();
        System.out.println(f1.get() + "=" + f2.get());
        context.shutdown();
    }
}
